package com.yangrd.airship.sys.web.modules.sys;

import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.StringExpression;
import com.yangrd.airship.common.jpa.BaseController;
import com.yangrd.airship.upms.domain.QRole;
import com.yangrd.airship.upms.domain.Role;
import com.yangrd.airship.upms.domain.RoleRepository;
import com.yangrd.airship.upms.support.AuthorizeDefine;
import com.yangrd.airship.upms.support.AuthorizeDescribe;
import com.yangrd.airship.upms.support.RoleAuthorizeHelper;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer;
import org.springframework.data.querydsl.binding.QuerydslBindings;
import org.springframework.data.querydsl.binding.QuerydslPredicate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.security.RolesAllowed;
import java.util.Collection;
import java.util.List;

/**
 * description: UserController
 *
 * @author: yangrd
 * @date: 2021/7/3
 * @version: 1.0
 */
@Api(tags = "系统管理-角色管理")
@AuthorizeDescribe({"系统管理", "角色管理"})
@RequiredArgsConstructor


@RestController
@RequestMapping("/api/sys/role")
public class RoleController extends BaseController<Role, Integer, RoleRepository> {

    @GetMapping("/authorize-defines")
    public Collection<AuthorizeDefine> listAuthorizeDefines() {
        return RoleAuthorizeHelper.listAuthorizeDefines("com.yangrd.airship.admin.web.modules");
    }

    @GetMapping("/list")
    public List<Role> list() {
        return repository.findAll();
    }

    @GetMapping
    @RolesAllowed("sys:role:view")
    public Page<Role> findAll(@QuerydslPredicate(root = Role.class, bindings = RoleQueryDslBinderCustomizer.class) Predicate predicate, Pageable pageable) {
        return repository.findAll(predicate, pageable);
    }

    static class RoleQueryDslBinderCustomizer implements QuerydslBinderCustomizer<QRole> {

        @Override
        public void customize(QuerydslBindings querydslBindings, QRole qRole) {
            querydslBindings.bind(qRole.name).first(StringExpression::contains);
        }
    }
}
